let ErrorUtils = require('../utils/error/ErrorUtils');
let {City} = require('../models');
const {infoLogger, errorLogger} = require('../config').logger;
const Joi = require('joi');

class CityService {

    /**
     * 获取城市列表
     * @returns {Promise<void>}
     */
    static async list() {
        infoLogger.info(">>>>>获取城市列表开始");
        return await City.find();
    }

    static checkCityData(data) {
        let schema = Joi.object({
            name: Joi.string().min(2).max(20).required(),
        });
        let result = Joi.validate(data, schema);
        return result;
    }

    /**
     * 城市添加
     * @returns {Promise<*>}
     */
    static async create(data) {
        infoLogger.info(">>>>>获取城市添加开始");
        await CityService.checkCityData(data);
        let result = await City.findOne({name: data.name});
        if (!result) {
            return await City.create(data);
        }
        return result;

    }

    /**
     * 城市删除
     * @returns {Promise<*>}
     */
    static async delete(id) {
        infoLogger.info(">>>>>获取城市添加开始");
        if (!id) {
            return false;
        }
        await City.remove({_id: id});
        return true;
    }
}

module.exports = CityService;
